<!--
 * @Author: ljc
 * @Date: 2024-01-24 13:48:08
 * @LastEditors: LiSong
 * @LastEditTime: 2024-09-14 14:26:19
 * @Description: pdf预览
-->
<template>
  <div style="height: 100%; width: 100%; overflow: hidden;">
    <PdfViewer :pdf="pdfFile" :show-download="false"/>
  </div>
</template>

<script setup>
import { useFileStore } from '@/stores/modules';
import { previewFile, fileType, openNewWindow, dowloadFile } from '@/utils/file-utils.js';
import { ElMessage, ElLoading } from 'element-plus'
import { nextTick, ref, watch, unref, onBeforeUnmount } from "vue";

import PdfViewer from './PdfViewer.vue'

// pdfStore
let fileStore = useFileStore()
const props = defineProps({
  // 文件Id
  fileId: { type: [String, Number], default: "" },
  // 文件名称
  title: { type: String, default: "" },
  // 文件地址Blob
  fileUrl: { type: String, default: "" },
  // 文件类型
  fileType: { type: String, default: "" },
  // 附件隐藏下载隐藏  true 不隐藏下载 false 隐藏下载
  expertFileDownload: {
    type: [Boolean],
    default: true,
  },
  // 文件返回结果
  fileResult: {
    type: Object,
    default: () => { }
  },
})
// pdf配置
// const config = reactive({
//   ...pdfConfig
// })
const vuePdfRef = ref(null)
let loading = ref(false)
// 文件类型
let reviewFileType = ref(props.fileType)
// pdf文件地址
const pdfFile = ref('')
// pdf加载回调
// const openHandler = (pdf) => {
//   loading.value = false
// }
/** 滚动到指定页面 */
const toPage = (pageNumber) => {
  const pageElement = document.getElementById(`viewer`);
  if (pageElement && pageElement.childNodes && pageElement.childNodes.length > 0) {
    let pageElementSub = pageElement.childNodes[pageNumber - 1]
    pageElementSub.scrollIntoView({ behavior: "smooth" });
  }
}
//** 下载文件 */ 
const download = async () => {
  // if (reviewFileType.value == "application/pdf") {
  //   let file = unref(pdfFile.value)
  //   let filename = pdfjsLib.getFilenameFromUrl(file)
  //   const a = document.createElement("a");
  //   if (!a.click) {
  //     throw new Error('DownloadManager: "a.click()" is not supported.');
  //   }
  //   a.href = file;
  //   a.target = "_parent";
  //   if ("download" in a) {
  //     a.download = filename;
  //   }
  //   (document.body || document.documentElement).append(a);
  //   a.click();
  //   a.remove();
  // }
}
/** 重新打开 */
const reloadOpen = async () => {
  const viewLoading = ElLoading.service({
    lock: true,
    text: '生成中...',
  })
  if (props.fileResult) {
    let url = null
    viewLoading.close()
    url = previewFile(props.fileResult, fileType.pdf)
    openNewWindow(url, props.title)
  } else {
    viewLoading.close()
    ElMessage({ message: '没有任何数据！', type: "warning" });
  }
}
/** 加载pdf文件地址Blob */
const setFileInfo = (v1, v2) => {
  setTimeout(() => {
    pdfFile.value = v2
    cacheFileInfo(v1, v2)
  }, 200);
}
/** 加载判断本地是否有pdf文件 */
const cacheFileInfo = (v1, v2) => {
  const item = {
    result: props.fileResult,
    fileId: v1,
    fileUrl: v2,
  }
  const fileItem = fileStore.getFileItem(v1) || null
  if (fileItem == null) {
    fileStore.setFileItem(item)
    setTimeout(() => {
      toPage(1)
    }, 300);
  }

}
const handlePaste = (event) => {
  // 禁用鼠标右键
  event.preventDefault()
  return false
}
/** 监听文件fileId和fileUrl */
watch(() => [props.fileId, props.fileUrl], (newValue, oldValue) => {
  if (newValue && newValue.length > 0 && oldValue == undefined) {
    const v1 = newValue[0]
    const v2 = newValue[1]
    nextTick(() => {
      setFileInfo(v1, v2)
    })
  }
  if (newValue && newValue.length > 0 && oldValue && oldValue.length > 0) {
    const v1 = newValue[0]
    const v2 = newValue[1]
    const v4 = oldValue[1]
    if (v4 != v2) {
      nextTick(() => {
        setFileInfo(v1, v2)
      })
    }
  }
}, { deep: true, immediate: true })

onMounted(() => {
  const root = document.documentElement;
  root.style.setProperty('--sidebar-width', '300px');
  nextTick(() => {
    // 消除pdf-vue-app警告信息progress
    let elements = document.querySelectorAll('[data-l10n-args]')
    elements.forEach(element => {
      const text = element.getAttribute('data-l10n-args')
      if (text.includes('progress')) {
        element.setAttribute('data-l10n-args', "{ \"progress\": 0 }")
      }
    })
  })
})
onBeforeUnmount(() => {
  pdfFile.value = ''
})
defineExpose({
  toPage,
  download,
  reloadOpen
})
</script>
<style lang="scss" scoped>
:deep(#viewerContainer) {
	left: 0 !important;
}
:deep(#sidebarContainer) {
	background: var(--pdf-toolbar-sidebar-color) !important;
}
:deep(.pdf-app #sidebarContainer) {
	width: var(--sidebar-width);
}
:deep(.pdf-app #thumbnailView) {
	width: calc(100% - 8px);
}
</style>